package com.example.wyh.intelcheckbash;

import android.app.ActionBar;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wyh.intelcheckbash.bluetoothchat.BluetoothChatFragment;
import com.example.wyh.intelcheckbash.common.SysExitUtil;
import com.example.wyh.intelcheckbash.sqlite.TaskDbHelper;
import com.example.wyh.intelcheckbash.task.CheckDefectActivity;
import com.example.wyh.intelcheckbash.task.DownloadTaskActivity;
import com.example.wyh.intelcheckbash.temptemperature.ThermometricActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Set;

/**
 * Created by WYH on 17/10/30.
 */

public class SettingActivity extends AppCompatActivity {
    BluetoothChatFragment mFragment = MainActivity.getInstance();
    String mConnectDeviceAddress = null;
    public  void  initActionBar(){
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("");
            actionBar.setDisplayShowHomeEnabled(false);
            actionBar.setDisplayShowCustomEnabled(true);
            LayoutInflater inflator = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflator.inflate(R.layout.actionbar_custom,new LinearLayout(SettingActivity.this),false);
            android.support.v7.app.ActionBar.LayoutParams layout = new android.support.v7.app.ActionBar.LayoutParams(
                    android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT, android.support.v7.app.ActionBar.LayoutParams.MATCH_PARENT);
            actionBar.setCustomView(v, layout);
            Toolbar parent = (Toolbar) v.getParent();
            parent.setContentInsetsAbsolute(0, 0);
        }

        TextView actionBarTitle = (TextView) findViewById(R.id.action_bar_title);
        actionBarTitle.setText("系统设置");

        ImageView title_logo = (ImageView)findViewById(R.id.title_logo_id);
        title_logo.setImageResource(R.drawable.set_title);

        RelativeLayout bar_back_btn =  (RelativeLayout) findViewById(R.id.bar_back_btn);
        bar_back_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              SettingActivity.this.finish();
            }
        });


    }
    public void initVersionCodeInFooter()
    {
        TextView main_footer_version_name = (TextView)findViewById(R.id.setting_footer_version_name);
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
            String appVersionName = info.versionName; // 版本名
            main_footer_version_name.setText("颐达科技 "+appVersionName);
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch blockd
            e.printStackTrace();
        }
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_activity);
        SysExitUtil.activityList.add(SettingActivity.this);
        initVersionCodeInFooter();
        mConnectDeviceAddress = getIntent().getStringExtra("mConnectDeviceAddress");
        initActionBar();
        showUserInfo();
        initButtonAction();

    }
    public void initButtonAction(){
        Button change_password_btn =(Button) findViewById(R.id.change_password_btn);
        change_password_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent updatePassword = new Intent(SettingActivity.this,UpdatePasswordActivity.class);
                startActivity(updatePassword);
//                showChangePassword();
            }
        });
        Button logout_btn = (Button) findViewById(R.id.logout_btn);
        logout_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });

        Button about_button = (Button)findViewById(R.id.about_button_id);
        about_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(SettingActivity.this,AboutActivity.class));
            }
        });
        Button select_device_btn = (Button)findViewById(R.id.equipment_select_btn);
        select_device_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent select_device = new Intent(SettingActivity.this,SelectDeviceActivity.class);
                startActivityForResult(select_device,2004);
            }
        });

        Button clear_memory_btn = (Button)findViewById(R.id.clear_memory);
        clear_memory_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //清除数据库中七天前的没用的数据
                deleteDataBeforeSevenDays();
            }
        });
    }

    public void deleteDataBeforeSevenDays()
    {
        TaskDbHelper taskDbHelper = new TaskDbHelper(SettingActivity.this);
        SQLiteDatabase db = taskDbHelper.getWritableDatabase();
        db.beginTransaction();
        String query = "time <= '" + HttpUtil.getSevenDaysDateString() +
                "' and user_id = '" + LocalStorage.getUserXtm(SettingActivity.this)
                + "'";
        db.delete("task", query, null);
        try {
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        db.close();
        HttpUtil.showToast(SettingActivity.this,"清除完成",750);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent data = new Intent();
            data.putExtra("mConnectDeviceAddress", mConnectDeviceAddress);
            this.setResult(1007, data);
            this.finish();
        }
        return  true;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2004)
        {
            String address = data.getStringExtra("select_device_address");
            Log.e("address",address +":"+mConnectDeviceAddress);
            if (address.equals(null) == false && address.equals("") == false)
            {
                if ((mConnectDeviceAddress != null && mConnectDeviceAddress.equals(address)) || address.equals("noSelectDevice") == true)
                {
                    finish();
                    return;
                }
//                mFragment.connectDeviceWithAddress(address);
//                mConnectDeviceAddress = address;
                LocalStorage.saveString(SettingActivity.this,"blueToothAddress",address);
                finish();
            }
            else
            {
                LayoutInflater layoutInflater = LayoutInflater.from(SettingActivity.this);
                final View layout = layoutInflater.inflate(R.layout.promot_alert,
                        null);

                final AlertDialog alertDialog = new AlertDialog.Builder(SettingActivity.this).setTitle("").setView(layout)
                        .setPositiveButton("",  new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        })
                        .setNegativeButton("", null).show();

                TextView alert_title = (TextView)layout.findViewById(R.id.promot_alert_title);
                alert_title.setText("没有配对的蓝牙设备！");
                Button confirm = (Button)layout.findViewById(R.id.promot_confirm);
                confirm.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialog.dismiss();
                    }
                });
            }

        }
    }

    public void showUserInfo() {
        JSONObject user = LocalStorage.getObject(SettingActivity.this, "User");
        TextView username = (TextView) findViewById(R.id.username);
        username.setText(getValueByKey(user, "userName"));
        TextView fullName = (TextView) findViewById(R.id.full_name);
        fullName.setText(getValueByKey(user, "usernamecn"));
        TextView department = (TextView) findViewById(R.id.department);
        department.setText(getValueByKey(user, "deptname"));
        TextView job = (TextView) findViewById(R.id.job);
        job.setText(getValueByKey(user, "jobs"));
    }
    public  String getValueByKey(JSONObject jsonObject, String key ){
        String value ;
        try {
            value = (String) jsonObject.get(key);
        } catch (JSONException e) {
            value = "";
            e.printStackTrace();
        }
        return value;
    }


 
    public  void logout(){
        LayoutInflater layoutInflater = LayoutInflater.from(SettingActivity.this);
        final View layout = layoutInflater.inflate(R.layout.alert_dialog,
                null);
//        try {
            final AlertDialog alertDialog = new AlertDialog.Builder(SettingActivity.this).setTitle("").setView(layout)
                    .setPositiveButton("",  new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .setNegativeButton("", null).show();

            TextView alert_title = (TextView)layout.findViewById(R.id.alert_title);
            alert_title.setText("确认要注销此账号吗？");
            Button confirm = (Button)layout.findViewById(R.id.alert_confirm);
            confirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                    LocalStorage.removeKey(SettingActivity.this, "User");
                    try {
                        String bluetoothAddress = LocalStorage.getString(SettingActivity.this,"blueToothAddress");
                        if (mFragment.mIsConnectedBlueTooth == true && bluetoothAddress.length() != 0)
                        {
                            mFragment.connectDeviceWithAddress(bluetoothAddress);
                        }
                    }catch (Exception e)
                    {

                    }
                    MainActivity.setIsConnectedInFail(false);




//                    try {
//                        if (mFragment.mIsConnectedBlueTooth == true)
//                        {
//                            try {
//                                mFragment.onDestroy();
//                            }catch (Exception e)
//                            {
//                                Log.e("setting mFragment.onDestroy()",e.getMessage());
//                            }
//                        }
//                    }catch (Exception e)
//                    {
//                        Log.e("setting mFragment is null",e.getMessage());
//                    }
//                    startActivity(new Intent(SettingActivity.this,MainActivity.class));
                    finish();
                }
            });
            Button cancle = (Button)layout.findViewById(R.id.alert_cancle);
            cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    alertDialog.dismiss();
                }
            });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}
